package com.project.common.screens;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import applicationDAO.Institute;

import com.mysql.jdbc.PreparedStatement;
import com.project.trac.R;

import core.modules.DatabaseConnector;

public class Registration extends Institute implements OnClickListener {

	private EditText inputStudentNo;
	private EditText inputUsername;
	private EditText inputEmail;
	private EditText inputPassword;
	private EditText inputRepeatPassword;
	private EditText inputLastName;
	private EditText inputFirstName;

	private Spinner spinner;
	private Button btn_submit;
	private Button btn_clear;
	private AlertDialog.Builder alertdialog;
	private TextView textview;
	private ArrayAdapter<CharSequence> adapter;
	private CheckBox showPassword;

	// trac.users
	private List<String> users_uname = new ArrayList<String>();
	private List<String> users_sid = new ArrayList<String>();
	private List<EditText> field = new ArrayList<EditText>();

	// EditText.toString() push to arrayList
	private String eUsername = "uname";
	private String ePassword = "pass";
	private String eRPassword = "rpass";
	private String eEmail = "email";
	private String eFirstName = "fname";
	private String eLastName = "lname";
	private String eStudentNo = "studentid";
	private String spinnerText = "course";

	// tags
	private String TAG_IDENTIFIER;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.commons_registration);

		TAG_IDENTIFIER = getIntent().getExtras().getString("TAG_IDENTIFIER");

		if (TAG_IDENTIFIER.equals("0")) {
			setTitle("New Faculty Member");
		} else {
			setTitle("New Student Registration");
		}

		/** Load users table to support validation */
		new AsynchronousTask("initialize").execute();

		// ========== EditText
		inputStudentNo = (EditText) findViewById(R.id.edit_R_StudentNo);
		inputUsername = (EditText) findViewById(R.id.edit_R_Username);
		inputEmail = (EditText) findViewById(R.id.edit_R_Email);
		inputPassword = (EditText) findViewById(R.id.edit_R_Password);
		inputRepeatPassword = (EditText) findViewById(R.id.edit_R_RepeatPassword);
		inputLastName = (EditText) findViewById(R.id.edit_R_LastName);
		inputFirstName = (EditText) findViewById(R.id.edit_R_FirstName);

		field.add(inputUsername); 
		field.add(inputPassword);
		field.add(inputEmail); 
		field.add(inputFirstName);
		field.add(inputLastName); 
		field.add(inputStudentNo);

		// ========== Spinner
		spinner = (Spinner) findViewById(R.id.edit_R_course_selector);

		if (TAG_IDENTIFIER.equals("0")) {

			TextView textStudentNo = (TextView) findViewById(R.id.text_R_Student);
			TextView textSpinner = (TextView) findViewById(R.id.text_R_spinner);

			inputStudentNo.setVisibility(View.GONE);
			textStudentNo.setVisibility(View.GONE);
			textSpinner.setText("Title : ");

			adapter = ArrayAdapter.createFromResource (this, R.array.honorifics, android.R.layout.simple_spinner_item);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		} 
		if (TAG_IDENTIFIER.equals("1")) {

			TextView textStudentNo = (TextView) findViewById(R.id.text_R_Student);
			TextView textSpinner = (TextView) findViewById(R.id.text_R_spinner);

			inputStudentNo.setVisibility(View.VISIBLE);
			textStudentNo.setVisibility(View.VISIBLE);
			textSpinner.setText("Course : ");

			adapter = ArrayAdapter.createFromResource (this, R.array.courses, android.R.layout.simple_spinner_item);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		}

		spinner.setAdapter(adapter);


		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> av, View view, int position, long id) {

				if (TAG_IDENTIFIER.equalsIgnoreCase("0")) {
					getResources().getStringArray(R.array.honorifics);
					spinnerText = av.getItemAtPosition(position).toString();
				} 
				if (TAG_IDENTIFIER.equalsIgnoreCase("1")) {
					getResources().getStringArray(R.array.courses);
					spinnerText = av.getItemAtPosition(position).toString();
				}

			}
			// ===== unused method
			public void onNothingSelected(AdapterView<?> arg0) {}

		});

		// ========== Buttons
		btn_clear = (Button) findViewById(R.id.clear);	
		btn_clear.setOnClickListener(this);

		btn_submit = (Button) findViewById(R.id.submit);
		btn_submit.setOnClickListener(this);

		// ========== CheckBox
		showPassword = (CheckBox) findViewById(R.id.edit_R_showpassword);
		showPassword.setOnClickListener(this);

	}

	@Override
	public void onBackPressed() {
		finish();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		// ========================================================= Show Password : Tick Box
		case R.id.edit_R_showpassword: {

			if (( (CheckBox) showPassword).isChecked()) {
				inputPassword.setTransformationMethod(null);
				inputRepeatPassword.setTransformationMethod(null);
			} else {
				inputPassword.setTransformationMethod(new PasswordTransformationMethod());
				inputRepeatPassword.setTransformationMethod(new PasswordTransformationMethod());
			}

			break;
		}

		// ========================================================= Clear Fields : Button
		case R.id.clear: {

			for (EditText et: field) {
				et.setText("");
			}

			break;
		}

		// ========================================================= Submit Registration : Button
		case R.id.submit: {

			eUsername = inputUsername.getText().toString();
			ePassword = inputPassword.getText().toString();
			eRPassword = inputRepeatPassword.getText().toString();
			eEmail = inputEmail.getText().toString();
			eFirstName = inputFirstName.getText().toString();
			eLastName = inputLastName.getText().toString();
			eStudentNo = inputStudentNo.getText().toString();

			// sql query fix to avoid NullPointerException
			spinnerText = spinner.getSelectedItem().toString();
			
			if (!ePassword.equals(eRPassword)) {
				inputRepeatPassword.setError("Passwords do not match!");
			}
			
			for (int i =0; i < users_uname.size(); i++) {
				if (eUsername.equalsIgnoreCase(users_uname.get(i))){
					inputUsername.setError("Username already taken.");
				}

				if (eStudentNo.equalsIgnoreCase(users_sid.get(i))){
					Toast.makeText(getBaseContext(), "Student number already registered.", Toast.LENGTH_LONG).show();
				}

			}
			
			
			if (checkEmptyFields() == true) {
				new AsynchronousTask("register").execute();
			}
			
			break; 
		}

		default: {
			Log.w("Revert to ", "default");
		}

		}// end switch
	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		Window window = getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}

	private class AsynchronousTask extends AsyncTask<String, String, String> {

		ResultSet rs;
		String command = "command";
		ProgressDialog progressDialog;
		
		PreparedStatement pps;
		
		boolean success;

		AsynchronousTask(String command) {
			this.command = command;
			doInBackground(command);
		}
		
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(Registration.this);
			progressDialog.setTitle("Please Wait");
			progressDialog.setIcon(android.R.drawable.ic_dialog_info);

			if (TAG_IDENTIFIER.equals("0")) {
				progressDialog.setMessage("Preparing Faculty Form...");
			} else {
				progressDialog.setMessage("Preparing Student Form...");
			}

			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.show();
		}

		protected String doInBackground(String... args) {
			
			try {
				
				if (command.equalsIgnoreCase("initialize")) {
					initialize();
				}
				
				if (command.equalsIgnoreCase("register")) {
					if (TAG_IDENTIFIER.equals("0")) {
						pps = (PreparedStatement) DatabaseConnector.getConnection().prepareStatement
						("INSERT INTO users(Username, Password, Email, Title, FirstName, LastName, isStudent) VALUES " 
								+ "(?,?,?,?,?,?,?)");
					
						pps.setString(1, eUsername);
						pps.setString(2, ePassword);
						pps.setString(3, eEmail);
						pps.setString(4, spinnerText);
						pps.setString(5, eFirstName);
						pps.setString(6, eLastName);
						pps.setInt(7, 0);
						
						pps.executeUpdate();
						pps.clearParameters();
						success = true;
					}
					
					if (TAG_IDENTIFIER.equals("1")) {
						pps = (PreparedStatement) DatabaseConnector.getConnection().prepareStatement
						("INSERT INTO users(Username, Password, Email, FirstName, LastName, StudentID, Course, isStudent) VALUES " 
								+ "(?,?,?,?,?,?,?)");
					
						pps.setString(1, eUsername);
						pps.setString(2, ePassword);
						pps.setString(3, eEmail);
						pps.setString(4, eFirstName);
						pps.setString(5, eLastName);
						pps.setString(6, eStudentNo);
						pps.setString(7, spinnerText);
						pps.setInt(8, 1);
						
						pps.executeUpdate();
						pps.clearParameters();
						success = true;
						
					}
					
				}
				
			} catch (SQLException e) {
				Log(getClass(), "doInBackground", e);
			}
			

			return null;
		}

		protected void onPostExecute(String postExecute) {

			progressDialog.dismiss();

			try {
				if (success == true) {

					textview = new TextView(getApplicationContext());
					alertdialog = new AlertDialog.Builder(Registration.this);
					textview.setTextAppearance(getApplication(), R.style.alert_message);
					textview.setGravity(Gravity.CENTER_HORIZONTAL);
					textview.setText("Registration success!");

					alertdialog.setTitle("Information").setIcon(android.R.drawable.ic_dialog_info);
					alertdialog.setCancelable(false);
					alertdialog.setView(textview) 
					.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 
						public void onClick(DialogInterface dialog, int id) { 
							dialog.dismiss(); 
							finish();
						} 
					}).create().show();	
				}

			} catch (Exception e){
				Log(getClass(), "onPostExecute", e);
			}
		}
		
		private void initialize() throws SQLException {
			
			rs = DatabaseConnector.getStatement().executeQuery("SELECT * FROM users");

			while (rs.next()) {
				users_uname.add(rs.getString("username"));
				users_sid.add(rs.getString("studentid"));
			}
			
			rs.close();
		}

	}

	private boolean checkEmptyFields() {
		
		for (EditText et: field) {
			if (et.getText().toString().length() == 0) {
				et.setError("Field is empty!");
			}
		}
		
		if (TAG_IDENTIFIER.equals("0")) {
			if ( (eUsername.length() != 0) & (ePassword.length() != 0)  &
					 (eEmail.length() != 0)    & (eFirstName.length() != 0) &
					 (eLastName.length() != 0)) { 
					//Log.i("Existing Fields - Teacher ", "true");
					return true;
				}
		}
		
		if (TAG_IDENTIFIER.equals("1")) {
			if ((eUsername.length() != 0) & (ePassword.length() != 0)
					& (eEmail.length() != 0) & (eFirstName.length() != 0)
					& (eLastName.length() != 0) & (eStudentNo.length() != 0)) {
				//Log.i("Existing Fields - Student", "true");
				return true;
			}
		}
		
		return false;

	}
}